package com.gujiangbo.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/5/3 21:21
 * @Version: 1.0
 * @Description: 使用Channel写数据到文件中
 */
public class JavaFileChannelWriteDemo {

    public static void main(String[] args) throws Exception {
        RandomAccessFile file = new RandomAccessFile("/Users/gujiangbo/Desktop/project/study-nio/src/main/resources/write.txt", "rw");
        // 获取文件通道
        FileChannel channel = file.getChannel();
        String msg = "new string to write the files.. the date: " + System.currentTimeMillis();
        // 定义一个字节缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.clear();
        // 将代写的字符串加入到缓冲区中
        buffer.put(msg.getBytes(StandardCharsets.UTF_8));
        // 反转读写模式
        buffer.flip();
        // 如果缓冲区中存在数据
        while (buffer.hasRemaining()) {
            // 字节将缓冲区数据写入到通道中
            channel.write(buffer);
        }
        // 写完后关闭通道
        channel.close();
    }
}
